#include "audiopage/audiopage.h"



extern Button2 Button_middle;
extern bool currentBtnState;
extern bool speakOut; 
extern bool previousBtnState;
extern lv_chart_series_t * AUDIO_PAGE_chart_2_0;
extern bool list_refresh_falg_send;


void  update_chart_with_i2s_data(lv_obj_t *chart, int16_t *samples_16bit, int sample_count)
{

    static lv_coord_t chart_data[16];
    // 每个图表点的样本数
    const int samples_per_point = 8;  // 128 / 16 = 8
    // 处理样本并更新图表数据
    for (int i = 0; i < 16; i++) {
        int32_t sum = 0;
        for (int j = 0; j < samples_per_point; j++) {
            int index = i * samples_per_point + j;
            // 使用 abs 将负值视为正值
            sum += abs(samples_16bit[index]);
        }
        
        // 计算平均值
        int32_t average = sum / samples_per_point;
        
        // 将平均值从 0-32767 缩放到 0-100
        int32_t scaled_value = (average * 100) / 32767;
        
        // 确保值在 0-100 范围内
        scaled_value = (scaled_value > 100) ? 100 : scaled_value;
        
        // 设置图表数据数组中的值
        chart_data[i] = scaled_value;
    }
    // 使用 lv_chart_set_ext_array 设置图表数据
    lv_chart_set_ext_array(chart,AUDIO_PAGE_chart_2_0, chart_data, 16);
    // 刷新图表
    lv_chart_refresh(chart);
}

void audio_send() {
    if (currentBtnState)
    {
    i2s_zero_dma_buffer(SPK_I2S_PORT);
    speakOut = 0;
    int samples_read = I2Sread(samples_16bit, 128);
    if(!audio_recive){//如果没有接收到音频数据
    covert_bit(samples_16bit, samples_8bit, samples_read);
    sendData(samples_8bit, samples_read);
    list_refresh_falg_send = true;
    }
    }
    currentBtnState = Button_middle.isPressed();
        if (previousBtnState && !currentBtnState && !audio_recive)
    {
      i2s_zero_dma_buffer(REC_I2S_PORT);
      sendStopSignal(); // 发送停止信号
    }
    previousBtnState = currentBtnState; // 更新按键状态
}


